package com.wzy.service.controller;

import com.wzy.common.base.Youdao.StreamSpeechDemo;
import com.wzy.common.base.Youdao.TranslationUtil;
import com.wzy.common.base.result.R;
import com.wzy.service.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/3/30 18:18
 * 4
 */

@RestController
@RequestMapping("/oss")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     * @param file
     */
    @PostMapping("upload")
    public R upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("module") String module) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String uploadUrl = fileService.upload(inputStream, module, originalFilename);
        //返回r对象
        System.out.println(uploadUrl);
        return R.ok().data("url", uploadUrl);
    }

    // 翻译视频
    @PostMapping("video")
    public R upload(@RequestParam("file") MultipartFile file) throws NoSuchAlgorithmException {

        String fileName = file.getOriginalFilename();
        File dest = new File(new File("D:\\test").getAbsolutePath()+ "\\" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 文件转化为wav格式
        String s1 = mp42wav(dest.getAbsolutePath());
        // 翻译wav视频
        String s = TranslationUtil.toTranslationVideo(s1);
        String filePath = "D:\\test\\srt\\" + UUID.randomUUID() + ".srt";
        StreamSpeechDemo.saveAsFileWriter(s, filePath);
        return R.ok().data("file", s).data("filename", UUID.randomUUID());
    }

    @GetMapping("getDown")
    public R getDownload(@RequestParam String url , HttpServletResponse response) throws UnsupportedEncodingException {
        //if (url != null) {
        //    //设置文件路径
        //    File file = new File(url);
        //    String f;
        //    if (file.exists()) {
        //        response.setContentType("application/force-download");// 设置强制下载不打开
        //        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(url, "UTF-8"));
        //
        //        response.setCharacterEncoding("UTF-8");
        //
        //        byte[] buffer = new byte[1024];
        //        FileInputStream fis = null;
        //        BufferedInputStream bis = null;
        //        try {
        //            fis = new FileInputStream(file);
        //            bis = new BufferedInputStream(fis);
        //            OutputStream os = response.getOutputStream();
        //            int i = bis.read(buffer);
        //            while (i != -1) {
        //                os.write(buffer, 0, i);
        //                i = bis.read(buffer);
        //            }
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        } finally {
        //            if (bis != null) {
        //                try {
        //                    bis.close();
        //                } catch (IOException e) {
        //                    e.printStackTrace();
        //                }
        //            }
        //            if (fis != null) {
        //                try {
        //                    fis.close();
        //                } catch (IOException e) {
        //                    e.printStackTrace();
        //                }
        //            }
        //        }
        //    }
        //}
        return R.ok().data("file", "0\n" +
                "00:00:01 --> 00:00:09\n" +
                "More than 2000 years ago, the people of Eurasia explored and opened up several routes of trade and cultural exchanges.\n" +
                "2000多年前，亚欧大陆人民开辟了多条贸易和文化交流的道路。\n" +
                "\n" +
                "1\n" +
                "00:00:10 --> 00:00:14\n" +
                "Which were called the Silk Road, by later generations.\n" +
                "后人称之为丝绸之路。\n" +
                "\n" +
                "2\n" +
                "00:00:20 --> 00:00:24\n" +
                "The Silk Road helped unravel the mystery of the ancient China.\n" +
                "丝绸之路帮助揭开了古代中国的神秘面纱。\n" +
                "\n" +
                "3\n" +
                "00:00:26 --> 00:00:31\n" +
                "Chinese tea was once sold abroad with the name of Oriental leaves.\n" +
                "中国茶叶曾以东方茶叶的名字销往国外。\n" +
                "\n");
    }


    String mp42wav(String sourcePath) {
        String webRoot = "C:\\Users\\wuzhengyu\\Desktop\\ffmpeg\\bin";
        Runtime run = null;
        run = Runtime.getRuntime();
        long start = System.currentTimeMillis();
        System.out.println(new File(webRoot).getAbsoluteFile());
        String outPath = "D:\\test\\out\\" + UUID.randomUUID() + ".wav";
        String cmd = new File(webRoot).getAbsoluteFile() + "\\ffmpeg.exe -i " + sourcePath + " -ar 16000 " + outPath;
        System.out.println(cmd);
        try {
            Process p = run.exec(cmd);
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.waitFor();
            long end=System.currentTimeMillis();
            System.out.println(sourcePath+" convert success, costs:"+(end-start)+"ms");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            run.freeMemory();
        }
        return outPath;
    }

}
